/**
 * 
 */
package jvs.core.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import x.java.io.FileOutputStream;

/**
 * @author qiangli
 * 
 */
public class Client {
	private URL context;

	/**
	 * @throws IOException 
	 * 
	 */
	public Client(String peer) throws IOException {
		this.context = new URL("peer:/"+"/");
	}

	public void getFile(String file, String to) throws Exception {
		InputStream is = null;
		FileOutputStream os = null;
		try {
			URL url = new URL(context, file);
			URLConnection conn = url.openConnection();
			is = conn.getInputStream();
			os = new FileOutputStream(to);
			int i;
			while ((i = is.read()) != -1) {
				os.write(i);
			}
			os.flush();
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			is.close();
			os.close();
		}
	}
	
	public String post(String cmd, String filepath, String options) throws IOException {

		try {
			URL url = new URL(context,cmd);
			URLConnection conn = url.openConnection();
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setUseCaches(false);
			conn.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			OutputStreamWriter out = new OutputStreamWriter(conn
					.getOutputStream());
			String data = "filepath=" + URLEncoder.encode(filepath, "UTF-8");
			if (options != null) {
				data += "&option=" + URLEncoder.encode(options, "UTF-8");
			}
			out.write(data);
			out.close();
			InputStream is = conn.getInputStream();
			Reader r = new InputStreamReader(is);
			StringBuilder sb = new StringBuilder();
			char[] ch = new char[256];
			int cnt = -1;
			while ((cnt = r.read(ch)) != -1) {
				sb.append(ch,0,cnt);
			}
			r.close();
			return sb.toString();
		} catch (IOException e) {
			throw e;
		}
		
	}
}
